import React, { useEffect, useState } from 'react';
import axios from 'axios';
import '../assets/styles/userTable.css';

const UserTable = () => {
  const [users, setUsers] = useState([]);
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    email: '',
    phone: '',
    points_balance: 0,
    role: '普通用户',
    wallet_address: '',

    
  });
  const [editingUserId, setEditingUserId] = useState(null); // 正在编辑的用户ID
  const [error, setError] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false); // 控制弹窗的显示

  useEffect(() => {
    fetchUsers();
  }, []);



  const fetchUsers = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/admin/users'); // 明确指定后端地址
      setUsers(response.data);
    } catch (error) {
      console.error('获取用户列表失败:', error.message);
      setError('获取用户列表失败，请稍后再试');
    }
  };


  const handleUpdate = async () => {
    const updates = {
      username: formData.username,
      email: formData.email,
      phone: formData.phone,
    };

    try {
      await axios.put(`http://localhost:5000/api/admin/users/${editingUserId}`, updates);
      fetchUsers(); // 刷新用户列表
      setIsModalOpen(false); // 关闭弹窗
      setEditingUserId(null); // 取消编辑状态
      setFormData({}); // 清空表单
    } catch (error) {
      console.error('更新用户失败:', error.message);
      setError('更新用户失败，请稍后再试');
    }
  };


  const handleDelete = async (userId) => {
    if (!window.confirm('确认删除该用户吗？')) return;
    try {
      await axios.delete(`http://localhost:5000/api/admin/users/${userId}`); // 明确指定后端地址
      fetchUsers();
    } catch (error) {
      console.error('删除用户失败:', error.message);
      setError('删除用户失败，请稍后再试');
    }
  };
  

  return (
    <div>
      <h3>用户管理</h3>
      {error && <div style={{ color: 'red' }}>{error}</div>} {/* 错误提示 */}
      <table border="1" cellPadding="5">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>积分余额</th>
            <th>钱包地址</th>
            <th>角色</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.user_id}>
              <td>{user.user_id}</td>
              <td>{user.username}</td>
              <td>{user.email}</td>
              <td>{user.phone}</td>
              <td>{user.points_balance}</td>
              <td>{user.wallet_address}</td>
              <td>{user.role}</td>
              <td>
              <button
                  onClick={() => {
                    setEditingUserId(user.user_id); // 设置正在编辑的用户ID
                    setFormData(user); // 填充表单数据
                    setIsModalOpen(true); // 显示弹窗
                  }}
                >
                  编辑
                </button>
                <button onClick={() => handleDelete(user.user_id)}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {/* 编辑表单 */}
      {isModalOpen && (
  <>
    <div className="modal-overlay" onClick={() => setIsModalOpen(false)}></div>
    <div className="modal">
      <div className="modal-header">编辑用户信息</div>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          handleUpdate(); // 提交表单数据
        }}
      >
        <input
          type="text"
          placeholder="用户名"
          value={formData.username}
          onChange={(e) => setFormData({ ...formData, username: e.target.value })}
        />
        <input
          type="email"
          placeholder="邮箱"
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
        />
        <input
          type="text"
          placeholder="电话"
          value={formData.phone}
          onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
        />
        <input
          type="number"
          placeholder="积分余额"
          value={formData.points_balance}
          disabled
        />
        <input
          type="text"
          placeholder="角色"
          value={formData.role}
          disabled
        />
        <input
          type="text"
          placeholder="钱包地址"
          value={formData.wallet_address}
          disabled
        />
        <div className="modal-actions">
          <button type="submit" className="save">保存修改</button>
          <button
            type="button"
            className="close"
            onClick={() => setIsModalOpen(false)}
          >
            关闭
          </button>
        </div>
      </form>
    </div>
  </>
)}

    </div>
  );
};

export default UserTable;
